import { Injectable } from '@angular/core';
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import {Router} from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import { environment } from '../../environments/environment';

import { NotificationService } from "../components/notification/notification.service";

@Injectable()
export class HttpInterceptorService {

  constructor(private http: Http,private router: Router,private notifyService:NotificationService) { 
    this.baseUrl  = environment.baseUrl || 'http://localhost:8080'
    console.log('baseUrl-------' + this.baseUrl)
  }

  private headers = new Headers({ 'Content-Type': 'application/json' });

  private options = new RequestOptions({ headers: this.headers,  withCredentials: true });

  public baseUrl:string;

  public post(url: string, params: any, host?) {
    return this.http.post(this.baseUrl + url, params, this.options)
      .toPromise()
      .then(res=>{this.toLogin(res);return this.handleSuccess(res)})
      .catch(res => this.handleError(res, url));
  }

  public get(url: string, host?): any {
    return this.http.get(this.baseUrl + url,this.options)
      .toPromise()
      .then(this.handleSuccess)
      .catch(res => this.handleError(res, url));
  }

  public obsPost(url: string, params?: any, host?): Observable<any> {
    return this.http.post(this.baseUrl + url, params, this.options)
                    .map(res=>{this.toLogin(res);return this.handleSuccess(res)})
                    .catch(res => Observable.throw(this.handleError(res, url)));
  }

  toLogin(res){
    if(res.json().errcode == 403){this.router.navigate(['/login'])}
  }

  handleSuccess(res: Response) {
    let body = res["_body"];
    return {
      data: res.json().data,
      msg: res.json().msg || '',
      errcode: res.json().errcode || '',
      status: res.status,
      result: res.json().result || false
    }
  };

  handleError(error, url) {
    if(url.includes('sysRest/userInfo/api')){this.router.navigate(['/login'])}
    if(!navigator.onLine){ location.reload() }
    let errorRes = error.json();
    this.notifyService.error(url,(errorRes.msg || '接口不存在') + '['+ errorRes.status +']')
    return {
      data: error.data,
      msg: error.message || '',
      errcode: error.errcode || '',
      status: error.status,
      result: error.result || false
    }
  }


}
